<template>
  <div class="pay-container">
    <div class="pay-content">
      <div class="pay-header">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 7h20v10H2z" stroke="#409eff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
        <h2>订单支付</h2>
      </div>

      <div class="pay-info">
        <div class="pay-card">
          <div class="pay-amount">
            <div class="amount-label">支付金额</div>
            <div class="amount-value">¥{{ payInfo.money || '--' }}</div>
          </div>
          <div class="pay-details">
            <div class="pay-item">
              <span class="label">订单号</span>
              <span class="value">{{ payInfo.payment_no || '-' }}</span>
            </div>
            <div class="pay-item">
              <span class="label">支付方式</span>
              <span class="value payment-type">
                <span class="icon" aria-hidden>💳</span>
                {{ getPayTypeName() }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <div class="qrcode-section">
        <div class="qrcode-container">
          <template v-if="payInfo.type === 'wxpay'">
            <img :src="qrDataUrl || placeholderData" alt="微信支付二维码" class="qrcode-image" />
            <div class="scan-tip">
              <span>请使用微信扫一扫</span>
            </div>
          </template>
          <template v-else-if="payInfo.type === 'alipay'">
            <img :src="qrDataUrl || placeholderData" alt="支付宝支付二维码" class="qrcode-image" />
            <div class="scan-tip">
              <span>请使用支付宝扫一扫</span>
            </div>
          </template>
          <template v-else>
            请选择支付方式
          </template>
        </div>

        <div class="countdown-container" v-if="remainingTime !== null">
          <div class="countdown-text">
            <span>支付倒计时</span>
            <span class="time">{{ minutes }}:{{ seconds }}</span>
          </div>

          <div class="countdown-progress">
            <div class="bar-outer">
              <div class="bar-inner" :style="{ width: percentage + '%' }"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useHead } from '#imports'

useHead({ title: '订单支付 - 生活工具' })

const payInfo = ref({
  money: '',
  return_url: '',
  type: '',
  payment_no: '',
  payment_id: '',
  email: ''
})

const remainingTime = ref(null)
const maxTime = ref(300) // 5 分钟
// 使用项目内静态图片（优先查找 /public/wxpay.png 与 /public/alipay.png），若不存在则使用内联占位图
const placeholderData = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="100%" height="100%" fill="%23f3f4f6"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="%23909999" font-size="14">二维码加载</text></svg>'
const qrDataUrl = ref('')
function buildImagePaths(type) {
  const base = type === 'wxpay' ? 'wxpay' : 'alipay'
  // public/ 下的文件在运行时以根路径提供，因此使用根相对路径
  return [
    `/${base}.png`
  ]
}
const qrCandidates = ref([])
const qrCandidateIndex = ref(0)

function resolveImageForType(type) {
  const paths = buildImagePaths(type)
  // 直接返回第一个存在的路径在浏览器中会被 404，如果图片不存在会回退占位。
  // 这里优先返回第一个路径，最终在模板中用 onerror 回退占位图。
  qrCandidates.value = paths
  qrCandidateIndex.value = 0
  return qrCandidates.value[0] || placeholderData
}

let checkInterval = null
let countdownTimer = null

// 模拟 articleApi（保留原接口调用方式，fetch 代替 axios）
const articleApi = {
  async postProductOrderNo(amount, product_id, product_name,email) {
    try {
      const res = await fetch(`/api/createproduct`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: Number(amount), product_id, product_name,email })
      })
      const json = await res.json()
      return json
    } catch (e) {
      // 回退 mock 数据
      return { payment_no: 'MOCK' + Date.now(), payment_id: 'MOCK_ID_' + Date.now() }
    }
  },
  async postOrderNoPayCheck(id) {
    try {
      const res = await fetch(`/api/paycheck2`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderId: id })
      })
      // 始终返回响应文本（与原 axios 的 response.data 行为保持文本返回）
      const text = await res.text()
      return text
    } catch (e) {
      return '等待支付'
    }
  }
}

function parseUrlParams() {
  if (typeof window === 'undefined') return
  const params = new URLSearchParams(window.location.search)
  payInfo.value = {
    money: params.get('money') || '',
    name: params.get('name') || '',
    product_id: params.get('product_id') || '',
    return_url: params.get('return_url') || '',
    type: params.get('type') || 'wxpay',
    email: params.get('email') || ''
  }
}

function getPayTypeName() {
  const map = { wxpay: '微信支付', alipay: '支付宝支付' }
  return map[payInfo.value.type] || '未知支付方式'
}

async function createOrder() {
  try {
    // 使用 product_id 与可选的 name 创建订单
    const order = await articleApi.postProductOrderNo(payInfo.value.money, payInfo.value.product_id, payInfo.value.name,payInfo.value.email)
    // 把返回的 payment_no 与 payment_id 写回 payInfo，供页面与回调使用
    payInfo.value.payment_no = order.payment_no || order.payment_id || (`TNO_${Date.now()}`)
    payInfo.value.payment_id = order.payment_id || order.payment_no || (`MOCK_ID_${Date.now()}`)
    // 使用静态图片（项目内提供），若没有图片可在浏览器端加载失败时回退到占位图
    qrDataUrl.value = resolveImageForType(payInfo.value.type)
    // 启动轮询与倒计时
    startCheckPay(order.payment_id || order.payment_no || ('MOCK_ID_' + Date.now()))
    startCountdown()
  } catch (e) {
    console.error(e)
  }
}


async function checkPay(payment_id) {
  try {
    const res = await articleApi.postOrderNoPayCheck(payment_id)
    if (res === '支付成功' || res === 'success' || (typeof res === 'string' && /success/i.test(res))) {
      await executeCallback()
      stopCheck()
      stopCountdown()
    }
  } catch (e) {
    console.error(e)
  }
}

function startCheckPay(payment_id) {
  let elapsed = 0
  const maxMs = maxTime.value * 1000
  stopCheck()
  checkInterval = setInterval(async () => {
    await checkPay(payment_id)
    elapsed += 5000
    if (elapsed >= maxMs) {
      stopCheck()
      stopCountdown()
    }
  }, 5000)
}

function stopCheck() {
  if (checkInterval) {
    clearInterval(checkInterval)
    checkInterval = null
  }
}

function startCountdown() {
  remainingTime.value = maxTime.value
  stopCountdown()
  countdownTimer = setInterval(() => {
    if (remainingTime.value > 0) remainingTime.value -= 1
    else stopCountdown()
  }, 1000)
}

function stopCountdown() {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

async function executeCallback() {
  if (!payInfo.value.return_url) return
  const params = new URLSearchParams()
  params.append('payment_no', payInfo.value.payment_no)
  // 然后跳转回调页
  const callbackUrl = payInfo.value.return_url.includes('?') ? `${payInfo.value.return_url}&${params.toString()}` : `${payInfo.value.return_url}?${params.toString()}`
  // 在客户端跳转
  if (typeof window !== 'undefined') window.location.href = callbackUrl
}

const minutes = computed(() => {
  if (remainingTime.value == null) return '00'
  return Math.floor(remainingTime.value / 60).toString().padStart(2, '0')
})
const seconds = computed(() => {
  if (remainingTime.value == null) return '00'
  return (remainingTime.value % 60).toString().padStart(2, '0')
})
const percentage = computed(() => {
  if (remainingTime.value == null) return 0
  return Math.max(0, Math.min(100, (remainingTime.value / maxTime.value) * 100))
})

onMounted(() => {
  parseUrlParams()
  // 仅在浏览器端创建订单
  if (typeof window !== 'undefined') {
    createOrder()
  }
})

onBeforeUnmount(() => {
  stopCheck()
  stopCountdown()
})

// 图片加载错误处理：尝试下一个候选路径，最后回退占位图
function onImgError(e) {
  try {
    qrCandidateIndex.value += 1
    const next = qrCandidates.value[qrCandidateIndex.value]
    if (next) {
      qrDataUrl.value = next
      // 让 img 再次尝试加载新的 src
      e.target.src = next
    } else {
      e.target.src = placeholderData
    }
  } catch (err) {
    e.target.src = placeholderData
  }
}
</script>

<style scoped>
.pay-container{ min-height:100vh; background-color:#f5f7fa; display:flex; justify-content:center; align-items:center; padding:20px }
.pay-content{ width:100%; max-width:480px; background:white; border-radius:16px; box-shadow:0 4px 16px rgba(0,0,0,.08); padding:32px }
.pay-header{ display:flex; align-items:center; justify-content:center; margin-bottom:32px; gap:12px }
.pay-header h2{ margin:0; font-size:24px; color:#303133; font-weight:600 }
.pay-info{ margin-bottom:32px }
.pay-card{ border-radius:12px; transition:all .3s ease; background:#fff; padding:0 }
.pay-amount{ text-align:center; padding:24px 0; border-bottom:1px dashed #e4e7ed; margin-bottom:24px }
.amount-label{ font-size:14px; color:#909399; margin-bottom:8px }
.amount-value{ font-size:32px; font-weight:600; color:#409eff }
.pay-details{ padding:0 16px }
.pay-item{ display:flex; align-items:center; padding:12px 0; font-size:14px }
.label{ width:80px; color:#909399 }
.value{ flex:1; color:#606266 }
.payment-type{ display:flex; align-items:center; gap:8px }
.qrcode-section{ display:flex; flex-direction:column; align-items:center }
.qrcode-container{ background:white; padding:24px; border-radius:12px; box-shadow:0 2px 12px rgba(0,0,0,.04); text-align:center; margin-bottom:24px }
.qrcode-image{ width:200px; height:200px; margin-bottom:16px; border-radius:8px; object-fit:cover }
.scan-tip{ display:flex; align-items:center; justify-content:center; gap:8px; color:#909399; font-size:14px }
.countdown-container{ width:100%; max-width:320px }
.countdown-text{ display:flex; justify-content:space-between; align-items:center; margin-bottom:8px; color:#909399; font-size:14px }
.countdown-text .time{ color:#f56c6c; font-weight:500 }
.bar-outer{ background:#f0f2f5; border-radius:6px; height:10px; overflow:hidden }
.bar-inner{ height:100%; background:linear-gradient(90deg,#ff8a65,#409eff); transition:width .3s linear }
</style>
